import {
  _decorator,
  Component,
  Collider2D,
  Contact2DType,
  IPhysics2DContact,
  Vec3,
} from "cc";
const { ccclass, property } = _decorator;

@ccclass("BaseBullet")
export class BaseBullet extends Component {
  @property
  static speed: number = 100;

  @property
  direction: number = 0; // 子弹飞行方向，0度表示向上，90度表示向右，以此类推

  @property
  static damage: number = 1;

  // 子弹运动轨迹回调函数类型定义
  protected moveCallback: (
    currentPosition: { x: number; y: number; z: number },
    direction: number,
    deltaTime: number
  ) => { x: number; y: number; z: number } = null;

  protected collider: Collider2D = null;

  // 设置运动轨迹回调函数
  setMoveCallback(
    callback: (
      currentPosition: { x: number; y: number; z: number },
      direction: number,
      deltaTime: number
    ) => { x: number; y: number; z: number }
  ) {
    this.moveCallback = callback;
  }

  start() {
    // 初始化碰撞体
    this.collider = this.getComponent(Collider2D);
    if (this.collider) {
      this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
    }
  }

  update(deltaTime: number) {
    const position = this.node.position;
    let newPosition;

    if (this.moveCallback) {
      // 使用自定义运动轨迹
      newPosition = this.moveCallback(position, this.direction, deltaTime);
    } else {
      // 默认直线运动
      const radian = (this.direction * Math.PI) / 180;
      newPosition = {
        x: position.x + Math.sin(radian) * BaseBullet.speed * deltaTime,
        y: position.y + Math.cos(radian) * BaseBullet.speed * deltaTime,
        z: position.z,
      };
      Vec3.lerp(newPosition, position, newPosition, 60 * deltaTime);
    }
    this.node.setPosition(newPosition.x, newPosition.y, newPosition.z);

    // 设置子弹旋转角度，使其朝向与飞行方向一致
    this.node.setRotationFromEuler(0, 0, -this.direction);

    // 根据方向判断边界
    const screenHeight = 800;
    const screenWidth = 500;
    if (
      newPosition.y > screenHeight ||
      newPosition.y < -screenHeight ||
      newPosition.x > screenWidth ||
      newPosition.x < -screenWidth
    ) {
      this.node.destroy();
    }
  }
  protected onBeginContact(
    selfCollider: Collider2D,
    otherCollider: Collider2D,
    contact: IPhysics2DContact | null
  ) {
    // 子类重写此方法实现具体的碰撞逻辑
  }

  protected onDestroy(): void {
    // 取消注册碰撞回调
    if (this.collider) {
      this.collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
    }
  }

  public static setSpeed(speed: number) {
    BaseBullet.speed = speed;
  }
}
